﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaProCost;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaProCost;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;
using YNTK.Common.Model.NPOI;
using YNTK.Common.Configuration;
using YNTK.DataEncryption;
using YNTK.ClayObject;
using YNTK.System.Interfaces.System;

namespace YNTK.SubDev.ZyOaProCost
{
    /// <summary>
    /// 项目成本服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev",Name = "ZyOaProCost", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaProCostService : IZyOaProCostService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaProCostEntity> _zyOaProCostRepository;
        private readonly IBillRullService _billRuleService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaProCostService"/>类型的新实例
        /// </summary>
        public ZyOaProCostService(
            ISqlSugarRepository<ZyOaProCostEntity> zyOaProCostRepository,
            IBillRullService billRuleService,
            IUserManager userManager)
        {
            _zyOaProCostRepository = zyOaProCostRepository;            
            _db = _zyOaProCostRepository.Context;
            _billRuleService = billRuleService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取项目成本
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaProCostEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaProCostInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取项目成本列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ZyOaProCostListQueryInput input)
        {
            var sidx = input.sidx == null ? "happendTime" : input.sidx;
            List<string> queryHappendTime = input.happendTime != null ? input.happendTime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startHappendTime = queryHappendTime != null ? Ext.GetDateTime(queryHappendTime.First()) : null;
            DateTime? endHappendTime = queryHappendTime != null ? Ext.GetDateTime(queryHappendTime.Last()) : null;
            var data = await _db.Queryable<ZyOaProCostEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.proName), p => p.ProName.Equals(input.proName))
                .WhereIF(!string.IsNullOrEmpty(input.costName), p => p.CostName.Contains(input.costName))
                .WhereIF(queryHappendTime != null, p => p.HappendTime >= new DateTime(startHappendTime.ToDate().Year, startHappendTime.ToDate().Month, startHappendTime.ToDate().Day, 0, 0, 0))
                .WhereIF(queryHappendTime != null, p => p.HappendTime <= new DateTime(endHappendTime.ToDate().Year, endHappendTime.ToDate().Month, endHappendTime.ToDate().Day, 23, 59, 59))
                .Select(it=> new 
                {
                    id = it.Id,
                    proName=it.ProName,
                    costId=it.CostId,
                    costName=it.CostName,
                    costType=it.CostType,
                    happendTime=it.HappendTime,
                    amount=it.Amount,
                    creater=it.Creater,
                    createTime=it.CreateTime,
                    desPerson=it.DesPerson,
                    desPersonName=it.DesPersonName,
                }).MergeTable().Select<ZyOaProCostListOutput>().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return TkPageResult<ZyOaProCostListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建项目成本
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaProCostCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaProCostEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.CostId = await _billRuleService.GetBillNumber("ZYCB");
            entity.Creater = _userManager.UserId;
            entity.CreateTime = DateTime.Now;  
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
		/// 获取项目成本无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] ZyOaProCostListQueryInput input)
        {
            var sidx = input.sidx == null ? "happendTime" : input.sidx;
            List<string> queryHappendTime = input.happendTime != null ? input.happendTime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startHappendTime = queryHappendTime != null ? Ext.GetDateTime(queryHappendTime.First()) : null;
            DateTime? endHappendTime = queryHappendTime != null ? Ext.GetDateTime(queryHappendTime.Last()) : null;
            var data = await _db.Queryable<ZyOaProCostEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.proName), p => p.ProName.Equals(input.proName))
                .WhereIF(!string.IsNullOrEmpty(input.costName), p => p.CostName.Contains(input.costName))
                .WhereIF(queryHappendTime != null, p => p.HappendTime >= new DateTime(startHappendTime.ToDate().Year, startHappendTime.ToDate().Month, startHappendTime.ToDate().Day, 0, 0, 0))
                .WhereIF(queryHappendTime != null, p => p.HappendTime <= new DateTime(endHappendTime.ToDate().Year, endHappendTime.ToDate().Month, endHappendTime.ToDate().Day, 23, 59, 59))
                .Select(it=> new 
                {
                    id = it.Id,
                    proName=it.ProName,
                    costId=it.CostId,
                    costName=it.CostName,
                    costType=it.CostType,
                    happendTime=it.HappendTime,
                    amount=it.Amount,
                    creater=it.Creater,
                    createTime=it.CreateTime,
                    desPerson=it.DesPerson,
                    desPersonName=it.DesPersonName,
                }).MergeTable().Select<ZyOaProCostListOutput>().OrderBy(sidx+" "+input.sort).ToListAsync();
                return data;
        }

        /// <summary>
		/// 导出项目成本
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] ZyOaProCostListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<ZyOaProCostListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.GetList(input));
                exportData = data.Solidify<TkPageResult<ZyOaProCostListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"成本编号\",\"field\":\"costId\"},{\"value\":\"项目名称\",\"field\":\"proName\"},{\"value\":\"成本名称\",\"field\":\"costName\"},{\"value\":\"成本类型\",\"field\":\"costType\"},{\"value\":\"发生时间\",\"field\":\"happendTime\"},{\"value\":\"实际费用(元)\",\"field\":\"amount\"},{\"value\":\"成本责任人\",\"field\":\"desPerson\"},{\"value\":\"相关成员\",\"field\":\"desPersonName\"},{\"value\":\"创建人\",\"field\":\"creater\"},{\"value\":\"创建时间\",\"field\":\"createTime\"},]".ToList<ParamsModel>();           
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "项目成本.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<ZyOaProCostListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "YNTK")
            };
            return output;
        }

        /// <summary>
        /// 更新项目成本
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaProCostUpInput input)
        {
            var entity = input.Adapt<ZyOaProCostEntity>();
            entity.Modifyer = _userManager.UserId;
            entity.ModifyTime = DateTime.Now;  
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除项目成本
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaProCostEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyOaProCostEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }
    }
}
